package com.wjh.api.service;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.wjh.alipay.config.AlipayConfig;
import com.wjh.base.BaseController;
import com.wjh.bean.Constants;
import com.wjh.bean.Result;
import com.wjh.dao.PaymentInfoDao;
import com.wjh.pojo.PaymentInfo;
import com.wjh.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.util.Date;

/**
 * @Author: 王金海
 * @Description:
 * @Date: Created by Administrator on 2018/6/22.
 * @Modified By:
 */
@RestController
public class PayServiceImpl extends BaseController implements PayService,Constants {

    @Autowired
    private PaymentInfoDao paymentInfoDao;
    @Override
    public Result createPayToken(@RequestBody PaymentInfo paymentInfo) {
        //1、创建订单
        paymentInfo.setCreated(new Date());
        paymentInfo.setUpdated(new Date());
        int type = paymentInfoDao.savePaymentType(paymentInfo);
        if (type<=0) {
            return error("创建订单失败");
        }
        //2、生成支付token
        String token = TokenUtils.getToken();
        String orderToken=ORDER_TOKEN+token;
        //3、存入redis返回 k为支付token v为订单ID
        Integer id = paymentInfo.getId();
        baseRedisService.setString(orderToken,id.toString(),ORDER_TOKEN_TIME);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("token", orderToken);
        return success(jsonObject);
    }

    @Override
    public Result findPayToken(@RequestParam("payToken") String payToken) throws UnsupportedEncodingException {
        //1、验证参数
        if (StringUtils.isEmpty(payToken)) {
            return error("token不能为空");
        }
        String payId = (String)baseRedisService.getString(payToken);
        if (StringUtils.isEmpty(payId)) {
            return error("支付已超时");
        }
        //2、查询订单
        PaymentInfo paymentInfo = paymentInfoDao.getPaymentInfo(Long.parseLong(payId));
        if (ObjectUtils.isEmpty(paymentInfo)) {
            return error("订单不存在或已超时");
        }
        //3、对接支付  返回form表单
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = paymentInfo.getOrderId();
        //付款金额，必填
        String total_amount = paymentInfo.getPrice()+"";
        //订单名称，必填
//        String subject="测试中文";
        String subject=paymentInfo.getSource();
//        String subject = new String(sub.getBytes("GBK"),"utf-8");
        //商品描述，可空
        String body ="";
//        String body = new String(request.getParameter("WIDbody").getBytes("ISO-8859-1"),"UTF-8");

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //若想给BizContent增加其他可选请求参数，以增加自定义超时时间参数timeout_express来举例说明
        //alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
        //		+ "\"total_amount\":\""+ total_amount +"\","
        //		+ "\"subject\":\""+ subject +"\","
        //		+ "\"body\":\""+ body +"\","
        //		+ "\"timeout_express\":\"10m\","
        //		+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求参数可查阅【电脑网站支付的API文档-alipay.trade.page.pay-请求参数】章节

        //请求
        try {
            String result = alipayClient.pageExecute(alipayRequest).getBody();
            //输出
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("payHtml",result);
            return success(jsonObject);
        } catch (AlipayApiException e) {
            return error("支付接口异常");
        }

    }
}
